import buffer from "node:buffer";
import type { Peer } from "crossws";
import { getQuery } from "ufo";
import { ref } from "vue";

const users = new Map<string, { online: boolean }>();
const count = ref(0)
export default defineWebSocketHandler({
  async upgrade(req) {
    console.log("[ws] upgrade", req?.url);
  },
  open(peer) {
    console.log("[ws] open", peer, JSON.stringify(peer.url), JSON.stringify(getQuery(peer.url)));
  },

  async message(peer, message) {
    // message type
    if (!message.isBinary) 
      console.log("[ws] string message", peer, JSON.stringify(message.rawData));
    
    else console.log("[ws] binary message", peer, message.rawData); 

    if (message.text().includes("ping")) {
      if (count.value >= 3) {
        count.value = 0
        peer.send("fin")
        return
      }
      count.value++; 
      peer.send(`pong#${count.value}`); 
    }
  },

  close(peer, event) {
    console.log("[ws] close", peer, event);
    console.log("closed metadata", peer.id, peer.url, getQuery(peer.url));
  },

  error(peer, error) {
    console.log("[ws] error", peer, error);
  },
});
